package com.gyms.base;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.classic.okhttp.base.OkHttpUtils;
import com.gyms.MyApplication;
import com.gyms.R;
import com.gyms.activity.CodeLoginActivity;
import com.gyms.activity.ReportActivity;
import com.gyms.activity.SetAreaActivity;
import com.gyms.activity.SetLocationActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.StatisticsManager;
import com.gyms.manager.TitleManager;
import com.gyms.view.swipeback.SwipeWindowHelper;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import utils.StringUtils;
import weight.CommonEmptyView;
import weight.loadingview.DialogUtil;

import static com.gyms.manager.TitleManager.TitleTheme.Blue;


/**
 * ltx
 */

public abstract class BaseActivity extends AppCompatActivity {
    protected Context mContext;
    private Unbinder unbinder;//饭注销

    protected ProgressDialog progressDialog; // 数据加载进度条

    public MyApplication mMyApplication;


    protected TitleManager mTitleManager;//用title管理类处理
    protected TitleManager.TitleTheme mTheme = Blue;

    //加载中等待提示
    public Dialog loadingView = null;

    protected final static int PAGESIZE = 10;
    protected int mPageIndex = 1;
    protected int mIsRefreshOrLoadMore = 0;//0是刷新1是加载更多

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 锁定竖屏
        mContext = this;
        setContentView(getLayoutResId());
        unbinder = ButterKnife.bind(this);
        mMyApplication = ((MyApplication) getApplication()).getInstance();

        setTitleTheme();
        if (null != findViewById(R.id.NavigationBar)) {
            mTitleManager = new TitleManager(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0), mContext, mTheme);
        }
        initView();
        needSavedInstanceState(savedInstanceState);
        setListener();
        processLogic();//网络请求
    }


    /**
     * 自定义等待框提示
     *
     * @param text
     */
    protected Dialog createLoadingView(String text, Boolean canceledOnTouchOutside) {
        loadingView = DialogUtil.createLoadingDialog(mContext, text, canceledOnTouchOutside);
        return loadingView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatisticsManager.startActivity(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatisticsManager.endActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);//activity 销毁后同一取消请求
        unbinder.unbind();
        if (loadingView != null) {
            loadingView.dismiss();
            loadingView = null;
        }
    }
    /*********************子类实现*****************************/
    /**
     * 加载页面layout
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 设置各种事件的监听器
     */
    protected abstract void setListener();

    /**
     * 业务逻辑处理，主要与后端交互（网络请求）
     */
    protected abstract void processLogic();

    /**
     * 设置标题配色
     */
    protected void setTitleTheme() {

    }

    public void needSavedInstanceState(Bundle savedInstanceState){

    }

    /**
     * 弹出Toast
     *
     * @param text 显示的文字
     */
    public void showToast(String text) {
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 设置标题
     *
     * @param title 标题
     */
    public void setTitle(String title) {
        mTitleManager.setTitle(title);
    }


    /**
     * 返回键
     */
    public void setBack() {
        View mBack = mTitleManager.setBack();
        if (mBack != null) {
            mBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }

    /**
     * 通过Class跳转界面
     * 是否需要销毁当前页面
     **/
    public void startActivity(Class<?> cls, boolean isFinish) {
        startActivity(cls, null, isFinish);
    }

    /**
     * 含有Intent跳转界面
     **/
    public void startActivity(Intent intent, boolean isFinish) {
        if (null == intent) {
            return;
        }
        startActivity(intent);
        ComponentName mComponentName=intent.getComponent();
        if(StringUtils.isNull(mComponentName)){//不是跳转到activity 拿不到类名
            return;
        }
        if(SetLocationActivity.class.getName().equals(intent.getComponent().getClassName())||SetAreaActivity.class.getName().equals(intent.getComponent().getClassName())||ReportActivity.class.getName().equals(intent.getComponent().getClassName())||CodeLoginActivity.class.getName().equals(intent.getComponent().getClassName())){//登录页面从上往下弹出
            overridePendingTransition(R.anim.activity_open, R.anim.activity_stay);
        }else {
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
        if (isFinish) {
            onBackPressed();
        }
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle, boolean isFinish) {
        Intent intent = new Intent();
        intent.setClass(mContext, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        if(SetLocationActivity.class.getSimpleName().equals(cls.getSimpleName())||SetAreaActivity.class.getSimpleName().equals(cls.getSimpleName())||ReportActivity.class.getSimpleName().equals(cls.getSimpleName())||CodeLoginActivity.class.getSimpleName().equals(cls.getSimpleName())) {//举报页面弹出
            overridePendingTransition(R.anim.activity_open, R.anim.activity_stay);
        }else {
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
        if (isFinish) {
            onBackPressed();
        }

    }

    /**
     * dialog dismiss
     */
    public void dialogDis() {
        if (null != loadingView) {
            loadingView.dismiss();
        }
    }

    /**
     * dialog & CommonEmptyView dismiss
     */
    public void dialogDis(View contentView,CommonEmptyView mSearchEmpty) {
        dismissEmptyView(contentView,mSearchEmpty);
        if (null != loadingView) {
            loadingView.dismiss();
        }
    }

    /**
     * 显示空界面或错误界面
     * @param mSearchEmpty
     * @param code  非-100为无内容界面，否则为无网络界面
     */
    protected void showEmptyView(View contentView,CommonEmptyView mSearchEmpty,int code) {
        if(!StringUtils.isNull(mSearchEmpty)) {
            if (code == Constants.NO_NET) {//无网络的状态
                mSearchEmpty.setImgContent(Constants.TYPE_FAIL);
                mSearchEmpty.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
            } else {
                mSearchEmpty.setVisibility(View.VISIBLE);//空页面出现
                contentView.setVisibility(View.GONE);
                mSearchEmpty.setFailText(Constants.SEARCH_FAIL_TEXT);
                mSearchEmpty.setImgContent(Constants.TYPE_NOME);
            }
        }
    }

    /**
     * 隐藏空界面
     *
     * @param mSearchEmpty 传自定义界面
     */
    protected void dismissEmptyView(View contentView,CommonEmptyView mSearchEmpty) {
        if(!StringUtils.isNull(mSearchEmpty)) {
            contentView.setVisibility(View.VISIBLE);
            mSearchEmpty.setVisibility(View.GONE);//空页面隐藏
        }
    }

    //-------------------------滑动返回Star--------------------------
    protected SwipeWindowHelper mSwipeWindowHelper;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(!supportSlideBack()) {
            return super.dispatchTouchEvent(ev);
        }
        if(mSwipeWindowHelper == null) {
            mSwipeWindowHelper = new SwipeWindowHelper(getWindow());
        }
        return mSwipeWindowHelper.processTouchEvent(ev) || super.dispatchTouchEvent(ev);
    }

    /**
     * 是否支持滑动返回
     *
     * @return
     */
    protected boolean supportSlideBack() {
        return true;
    }
    //-------------------------滑动返回End--------------------------

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }


    /**
     * 隐藏软键盘
     * @param ev
     * @return
     */
    public boolean hideKeyBoard(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    v.clearFocus();
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }

        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop =
                    {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
